package com.unitd.frame.springweb.plugins.velocity.directive;

import com.unitd.frame.springweb.plugins.velocity.tools.RelativeDateTool;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.apache.velocity.tools.view.ViewToolContext;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;

/**
 * @desc 自定义一个Velocity的指令类, 用于自定义时间格式话对象
 * @filename RelativeDateFormatDirective.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/4/2
 */
public class RelativeDateFormatDirective extends AbstractDirective {

	public RelativeDateFormatDirective() {
	}

	@Override
	public String getName() {
		return "relativeDateFormat";
	}

	@Override
	public int getType() {
		return 2;
	}

	@Override
	protected boolean doRender(InternalContextAdapter internalContext, ViewToolContext context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
		SimpleNode sn = (SimpleNode) node.jjtGetChild(0);
		Date date = (Date) sn.value(internalContext);
		writer.write(RelativeDateTool.format(date));
		return true;
	}
}